# 获取设备数据,已有webSocket代替了
import json
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from app01.models import DeviceData
from collections import defaultdict


@require_GET
def device_data(request):
    # 参数校验
    device_name = request.GET.get('device_name')
    product_key = request.GET.get('product_key')
    sendOrReceive = request.GET.get('sendOrReceive')   # 上报成功过1,还是接收成功0
    Identifier = request.GET.get('Identifier').strip()

    if not all([device_name, product_key]):
        return JsonResponse(
            {'error': '缺少必需的参数'},
            status=400
        )

    try:
        # 数据查询: 全部
        queryset = DeviceData.objects.filter(
            deviceName=device_name,
            productKey=product_key
        ).filter(
            sendOrReceive=sendOrReceive  # 过滤出是要接收还是上报数据
        ).order_by('-gmtCreate')[:20]  # 限制100条最新数据

        result = defaultdict(list)
        for item in queryset:
            it = json.loads(item.items)   # 序列化,因为items是TextField,最好模型改成JSONField
            if it:
                for device_type, data in it.items():
                    if device_type and data:
                        if Identifier and device_type == Identifier:
                            result[device_type].append({
                                'value': data['value'],
                                'time': data['time']
                            })
                        if not Identifier:
                            result[device_type].append({
                                'value': data['value'],
                                'time': data['time']
                            })
        return JsonResponse(dict(result), safe=False)

    except Exception as e:
        return JsonResponse(
            {'error': str(e)},
            status=500
        )


